//
//  DevFormTextContentField.swift
//  csjf
//
//  Created by dev on 15/10/15.
//  Copyright © 2015年 devilved. All rights reserved.
//

import UIKit

class DevFormTextContentField:DevFormField {
    
    private var valueTextLabel:UILabel?
    
    var textFont:UIFont?
    
    var getTextFromValue:(AnyObject?) -> String? = {(value:AnyObject?) -> String? in return value as? String}
    
    override func initDevFormFieldView() {
        super.initDevFormFieldView()
        let main:UIView = self.view!
        let width:CGFloat = self.formTableView.frame.width
        let left:CGFloat = self.textLabel!.frame.origin.x + self.textLabel!.frame.width
        let right:CGFloat = self.formTableView.separatorInset.right > 0 ? self.formTableView.separatorInset.right : 15
        
        self.valueTextLabel = UILabel()
        let valueText = self.valueTextLabel!
        if let font:UIFont = self.textFont {
            valueText.font = font
        }
        
        valueText.textColor = UIColor.lightGrayColor()
        valueText.textAlignment = NSTextAlignment.Right
        valueText.frame = CGRectMake(left, (self.height - self.controlHeight) / 2, width - left - right, self.controlHeight)
        valueText.text = self.getTextFromValue(self.defaultValue)
        main.addSubview(valueText)
        
    }
    
    override func initConstraints() {
        let main:UIView = self.view!
        let valueText = self.valueTextLabel!
        
        let right:CGFloat = self.formTableView.separatorInset.right > 0 ? self.formTableView.separatorInset.right : 15
        
        valueText.translatesAutoresizingMaskIntoConstraints = false
        
        main.addConstraint(NSLayoutConstraint(item: valueText, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.textLabel!, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        
        main.addConstraint(NSLayoutConstraint(item: valueText, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: main, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        main.addConstraint(NSLayoutConstraint(item: main, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: valueText, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: right))
    }
    
    override func setFieldValue(value: AnyObject?) {
        super.setFieldValue(value)
        self.valueTextLabel?.text = self.getTextFromValue(value)
    }
    
    override func click() {
        self.formTableView.endEditing(true)
        self.focus()
    }
    
    func getText() -> String? {
        return self.getTextFromValue(self.getFieldValue())
    }
    
}